package com.example.cc.mygit.view.commit;

import com.example.cc.mygit.GitApplication;
import com.example.cc.mygit.model.Commit;
import com.example.cc.mygit.model.Project;
import com.example.cc.mygit.model.User;
import com.example.cc.mygit.source.API;
import com.haibin.elegant.Response;
import com.haibin.elegant.call.CallBack;

import java.util.List;

/**
 * Created by cc on 2017/1/1.
 */

public class CommitPresenter implements CommitContract.Presenter{
    private final CommitContract.View mView;
    private User mUser;
    private Project mProject;
    private int mPage = 1;

    public CommitPresenter(CommitContract.View mView, Project mProject) {
        this.mView = mView;
        this.mUser = GitApplication.getConfig().getUser();
        this.mProject = mProject;
        this.mView.setPresenter(this);
    }

    @Override
    public void onRefreshing() {
        API.getBranchs(mProject.getId(), mUser.getPrivateToken(), 1, new CallBack<List<Commit>>() {
            @Override
            public void onResponse(Response<List<Commit>> response) {
                List<Commit> commits = response.getBody();
                if (commits != null){
                    mView.onRefreshSuccess(commits);
                    mPage = 2 ;
                    if (commits.size()<20){
                        mView.showNoMoreData();
                    }
                }
                mView.onComplete();
            }

            @Override
            public void onFailure(Exception e) {
                mView.showNetWorkError();
                mView.onComplete();
            }
        });

    }

    @Override
    public void onLoadMore() {
        API.getBranchs(mProject.getId(),
                mUser.getPrivateToken(),
                mPage,
                new CallBack<List<Commit>>() {
                    @Override
                    public void onResponse(Response<List<Commit>> response) {
                        List<Commit> commits = response.getBody();
                        if (commits != null) {
                            mView.onLoadMoreSuccess(commits);
                            ++mPage;
                            if (commits.size() < 20) {
                                mView.showNoMoreData();
                            }
                        }
                        mView.onComplete();
                    }

                    @Override
                    public void onFailure(Exception e) {
                        mView.showNetWorkError();
                        mView.onComplete();
                    }
                });

    }

    @Override
    public void start() {

    }
}
